<?php
/*
 * coding: utf-8
 * +-------------------------------------------------------------------
 * | KL库 - BT模块
 * +-------------------------------------------------------------------
 * | Copyright (c) 2022-2099 KL库(https://www.fangheyun.xyz) All rights reserved.
 * +-------------------------------------------------------------------
 * | Author: 远易 <3431628590@qq.com>
 * +-------------------------------------------------------------------
 */
if(BT_SWITCH){
    class BT {
        /**
         * 宝塔面板操作函数
         */
        public function use($BT_PANEL,$BT_KEY,$Interface,$Data){
            if($BT_PANEL == ""){
                exit("ERROR: Pagoda address cannot be empty!");
            }else if($BT_KEY == ""){
                exit("ERROR: Pagoda key cannot be empty!");
            }else if($Interface == ""){
                exit("ERROR: Pagoda interface cannot be empty!");
            }else{
                //拼接URL地址
                $url = $BT_PANEL.'/'.$Interface;
                //准备POST数据
                if(is_array($Data)){
                    if(count($Data) > 0){
                        $p_data = array_merge($this->GetKeyData($BT_KEY),$Data);
                    }else{
                        $p_data = $this->GetKeyData($BT_KEY);
                    }
                }else{
                    $p_data = $this->GetKeyData($BT_KEY);
                }
                // 返回数据
                return $this->HttpPostCookie($url,$p_data,60,$BT_PANEL);
            }
        }
        /**
         * 获取宝塔签名
         */
        private function GetKeyData($BT_KEY){
            $now_time = time();
            $p_data = [
                'request_token' => md5($now_time.''.md5($BT_KEY)),
                'request_time' => $now_time
            ];
            return $p_data;
        }
        /**
         * 交给宝塔云端执行
         */
        private function HttpPostCookie($url,$data,$timeout = 60,$BT_PANEL)
        {
            //定义cookie保存位置
            $cookie_file = SYSTEM_ROOT.'cache/'.md5($BT_PANEL).'.cookie';
            if(!file_exists($cookie_file)){
                $fp = fopen($cookie_file,'w+');
                fclose($fp);
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }
	}
}
?>